package cn.wolfcode.wolf2w.strategy.service.impl;

import cn.wolfcode.wolf2w.destination.api.domain.Destination;
import cn.wolfcode.wolf2w.strategy.api.domain.Strategy;
import cn.wolfcode.wolf2w.strategy.api.domain.StrategyRank;
import cn.wolfcode.wolf2w.strategy.mapper.StrategyRankMapper;
import cn.wolfcode.wolf2w.strategy.query.StrategyRankQuery;
import cn.wolfcode.wolf2w.strategy.service.IStrategyRankService;
import cn.wolfcode.wolf2w.strategy.vo.ThemeVO;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.*;
import java.util.stream.Collectors;

/**
 * 攻略排行Service业务层处理
 *
 * @author dalang
 * @date 2023-11-24
 */
@Service
@Transactional
public class StrategyRankServiceImpl extends ServiceImpl<StrategyRankMapper, StrategyRank> implements IStrategyRankService {
    @Autowired
    private StrategyServiceImpl strategyService;

    @Override
    public IPage<StrategyRank> queryPage(StrategyRankQuery qo) {
        IPage<StrategyRank> page = new Page<>(qo.getCurrentPage(), qo.getPageSize());
        return lambdaQuery()
                .page(page);
    }

    @Override
    public List<StrategyRank> queryRankByType(int type) {
        List<StrategyRank> list = lambdaQuery().eq(StrategyRank::getType, type)
                .inSql(StrategyRank::getStatisTime, "(SELECT MAX(statis_time) from ta_strategy_rank where type = " + type + ")")
                .orderByDesc(StrategyRank::getStatisnum)
                .last("limit 10")
                .list();
        return list;
    }

    @Override
    public void strategyRankHandle(int type) {
        Date date = new Date();
        QueryWrapper<Strategy> wrapper = new QueryWrapper<>();
        if (type == StrategyRank.TYPE_HOT) {
//            List<Strategy> list = strategyService.lambdaQuery().eq(Strategy::getIsabroad, Strategy.ABROAD_YES).list();
            wrapper.orderByDesc("viewnum + replynum");

        } else {
            wrapper.eq("isabroad", type == StrategyRank.TYPE_CHINA ? Strategy.ABROAD_NO : Strategy.ABROAD_YES);
            wrapper.orderByDesc("thumbsupnum + favornum");

        }
//        else if (type == StrategyRank.TYPE_CHINA) {
//            wrapper.eq("isabroad", Strategy.ABROAD_NO);
//            wrapper.orderByDesc("thumbsupnum + favornum");
//
//        } else if (type == StrategyRank.TYPE_ABROAD) {
//            wrapper.eq("isabroad", Strategy.ABROAD_YES);
//            wrapper.orderByDesc("thumbsupnum + favornum");
//        }
        wrapper.last("limit 10");
        List<Strategy> list = strategyService.list(wrapper);

        List<StrategyRank> ranks = new ArrayList<>();
        for (Strategy strategy : list) {
            StrategyRank sr = new StrategyRank();
            sr.setDestId(strategy.getDestId());
            sr.setDestName(strategy.getDestName());
            sr.setStrategyId(strategy.getId());
            sr.setStrategyTitle(strategy.getTitle());
            sr.setType(type);
            sr.setStatisTime(date);
            if (type == StrategyRank.TYPE_HOT) {
                sr.setStatisnum(strategy.getViewnum() + strategy.getReplynum());
            } else {
                sr.setStatisnum(strategy.getThumbsupnum() + strategy.getFavornum());
            }
//            super.save(sr);
            ranks.add(sr);
        }
        super.saveBatch(ranks);

    }

    @Override
    public void strategyRankDelete() {
        Calendar start = Calendar.getInstance();
        start.set(Calendar.HOUR_OF_DAY, 0);
        start.set(Calendar.MINUTE, 0);
        start.set(Calendar.SECOND, 0);
        start.set(Calendar.MILLISECOND, 0);

        // 获取今天的23点59分
        Calendar end = Calendar.getInstance();
        end.set(Calendar.HOUR_OF_DAY, 23);
        end.set(Calendar.MINUTE, 59);
        end.set(Calendar.SECOND, 59);
        end.set(Calendar.MILLISECOND, 999);

        QueryWrapper<StrategyRank> wrapper = new QueryWrapper<>();
//        wrapper.inSql("DATE(statis_time)","CURDATE()");
        wrapper.gt("statis_time", start);
        wrapper.lt("statis_time", end);
        wrapper.notInSql("statis_time", "(SELECT MAX(statis_time) from ta_strategy_rank where DATE(statis_time) = CURDATE())");
        List<StrategyRank> list = super.list(wrapper);
//        list.stream().map(StrategyRank::getId).collect(Collectors.toList())
        super.removeByIds(list.stream().map(StrategyRank::getId).collect(Collectors.toList()));
    }

    @Override
    public List<ThemeVO> theme() {
        List<ThemeVO> vos = new ArrayList<>();
        QueryWrapper<Strategy> wrapper = new QueryWrapper<>();
        wrapper.select("theme_id, theme_name, count(theme_id) count, GROUP_CONCAT(id SEPARATOR \"<#>\") ids");
        wrapper.groupBy("theme_id, theme_name");
        wrapper.orderByAsc("theme_name");
        List<Map<String, Object>> maps = strategyService.listMaps(wrapper);

        for (Map<String, Object> map : maps) {
            ThemeVO vo = new ThemeVO();
            vo.setThemeName(map.get("theme_name").toString());
            String ids = map.get("ids").toString();
            List<Strategy> list = this.toStrategyList(ids);
            vo.setDests(list);

            vos.add(vo);
        }

        return vos;
    }

    private List<Strategy> toStrategyList(String ids) {
        List<Long> idsArrays = Arrays.stream(ids.split("<#>")).map(Long::parseLong).collect(Collectors.toList());
        return strategyService.listByIds(idsArrays);
    }
}
